﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace KC.ExtensionMethods
{
	public static class DataObjects
	{
		/// <summary>Inserts a DataColumn into a table anywhere you want it.</summary>
		/// <param name="col">This DataColumnCollection (i.e. DataTable.Columns[])</param>
		/// <param name="dc">Column to insert</param>
		/// <param name="Index">Where to insert it</param>
		public static void AddAt(this DataColumnCollection col, DataColumn dc, int Index)
		{
			if (dc == null) throw new ArgumentNullException("dc");
			if (Index > col.Count) throw new ArgumentOutOfRangeException("Index", Index, "Can't fit Index inside ColumnCollection. Please specify a location that will fit inside the number of columns.");

			using (DataTable dt = new DataTable()) {	
				// Rebuild column layout
				for (int i = 0; i <= col.Count; i++)  { // Unusually, the <= operator here is not a bug.
					if (i < Index) dt.Columns.Add(new DataColumn(col[i].ColumnName, col[i].DataType));
					else if (i == Index) dt.Columns.Add(new DataColumn(dc.ColumnName, dc.DataType));
					else dt.Columns.Add(new DataColumn(col[i - 1].ColumnName, col[i - 1].DataType)); }
				
				// Put the columns back into the original table.  This is the tricky part because ColumnCollections are read-only for some reason.
				col.Clear();
				foreach (DataColumn d in dt.Columns)
					col.Add(new DataColumn(d.ColumnName, d.DataType));

				// TODO: Figure out a way to do this noninvasively; i.e. without losing data.
				// Might have to pass in the whole fucking table. That would be an evil shame.
			}
		}
		
	}
}
